#include "Udp_Server.hpp"
#include <unordered_map>
#include <stdio.h>
#include <string.h>
#include <unordered_map>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
std::unordered_map<std::string,std::string> dict;

void Translate(const std::string& req,std::string* reps){
    *reps = "未查到!";
    if(dict.count(req)){
        *reps = dict[req];
    }
}

int main(int argc,char* argv[]){
    if(argc!=3){
        printf("Usage ./dict_server [ip] [port]\n");
        return 1;
    }
    /*
    dict["hello"] = "你好";
    dict["world"] = "世界";
    dict["c++"] = "最好的编程语言";
    */
    int fd = open("./words.txt",O_RDONLY);
    if(fd<0){
        perror("open words.txt");
        return -1;
    }
    char buff[1024];
    size_t n = read(fd,buff,sizeof(buff)-1);
    buff[n] = '\0';
    char* st = buff;
    while(*st){
        char* ed = strchr(st,'\n');
        char* m = strchr(st,':');
        *m = *ed = '\0';
        dict[std::string(st)] = std::string(m+1);
        st = ed+1;
    }
    // for(auto& it : dict){
    //     std::cout<<it.first << ":" << it.second<<std::endl;
    // }
    UdpServer server(argv[1],std::stoi(argv[2]),&Translate);
    server.Start();
    return 0;
}